package com.doradance.app.mine;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.LinearGradient;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.internal.http.multipart.FilePart;
import com.android.internal.http.multipart.Part;
import com.android.tu.loadingdialog.LoadingDailog;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.doradance.R;
import com.doradance.account.UrlCenter;
import com.doradance.account.utils.MultipartRequest;
import com.doradance.app.appactivity.AddBabyActivity;
import com.doradance.app.appactivity.LQRPhotoSelectUtils;
import com.doradance.app.home.CoursesDetailActivity;
import com.doradance.common.http.MyHttpRequest;
import com.doradance.entity.EventModifyPhone;
import com.doradance.entity.MineModifyEntity;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.dialog.IOSAlertListFragment;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.pachong.android.frameworkbase.utils.io.SharePreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

import static com.doradance.app.appactivity.LQRPhotoSelectUtils.REQ_COVER_TAKE_PHOTO;
import static com.doradance.app.appactivity.LQRPhotoSelectUtils.REQ_SELECT_PHOTO;
import static com.doradance.app.appactivity.LQRPhotoSelectUtils.REQ_TAKE_PHOTO;
import static com.doradance.app.appactivity.LQRPhotoSelectUtils.REQ_ZOOM_PHOTO;
import static com.doradance.app.mine.ModifyNicknameActivity.BACKNICKNAMECODE;
import static com.doradance.app.mine.ModifyNicknameActivity.NICKNAME;
import static com.doradance.app.mine.ModifyNicknameActivity.NICKNAMECODE;

public class EditPersionActivity extends BaseActivity {
    @Bind(R.id.civ_head)
    CircleImageView mCivHead;
    @Bind(R.id.tv_nick_name)
    TextView mTvNickName;
    @Bind(R.id.tv_red_phone)
    TextView mTvRedPhone;
    LoadingDailog upDialog;
    public static final int REQ_TAKE_MINE_PHOTO =10010;
    public static final int REQ_MINE_SELECT_PHOTO=10011;
    private LQRPhotoSelectUtils mLqrPhotoSelectUtils;
    String avater;
    String phone;
    String nickname;
    private String nickname1="";
    private String avater1="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        initToolsBar();
        avater = getIntent().getStringExtra("avater");
        nickname = getIntent().getStringExtra("nickname");
        nickname1=nickname;
        avater1=avater;
        phone = getIntent().getStringExtra("phone");
        initView();
    }

    private void initView() {
        mTvNickName.setText(nickname1);
        if(TextUtils.isEmpty(phone)){

        }else{
            mTvRedPhone.setText(phone);
        }
        if (!TextUtils.isEmpty(avater1)) {
            Glide.with(this).load(avater1).centerCrop().into(mCivHead);
        } else {
            Glide.with(this).load(R.mipmap.init_logo).centerCrop().into(mCivHead);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initToolsBar() {
        setTitle(getString(R.string.edit_persion_info));
        getCustomToolbar().addRightButton("保存", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                savePersionInfo();
            }
        });
        getCustomToolbar().addLeftImageButton(R.mipmap.back, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!nickname1.equals(mTvNickName.getText().toString())||!avater1.equals(avater)){
                    backDialog(EditPersionActivity.this);
                }else{
                    finish();
                }

            }
        });
    }





    private static void backDialog(final Activity mContext){
        LayoutInflater factory = LayoutInflater.from(mContext);
        View inflate = factory.inflate(R.layout.modify_nick_dialog, null);
        final AlertDialog isMemberDialog = new AlertDialog.Builder(mContext)
                .setView(inflate).create();
        inflate.findViewById(R.id.tv_cancel_modify).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isMemberDialog.cancel();
            }
        });
        inflate.findViewById(R.id.tv_no_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.finish();
                isMemberDialog.cancel();

            }
        });
        //设置点击Dialog外部任意区域关闭Dialog
        isMemberDialog.setCanceledOnTouchOutside(true);
        isMemberDialog.show();
    }



    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_edit_persion, null);
    }

    public static void start(Activity activity, String avater, String nickname, String phone) {
        Intent intent = new Intent(activity, EditPersionActivity.class);
        intent.putExtra("avater", avater);
        intent.putExtra("nickname", nickname);
        intent.putExtra("phone", phone);
        activity.startActivity(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventModifyPhone refreshEvent){
        mTvRedPhone.setText(refreshEvent.phone);
    }

    @OnClick({R.id.civ_head, R.id.ll_nick_name, R.id.ll_tele_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.civ_head:
                showIOSAlertFrag();
                break;
            case R.id.ll_nick_name:
                ModifyNicknameActivity.start(EditPersionActivity.this, mTvNickName.getText().toString());
                break;
            case R.id.ll_tele_phone:
                BindPhoneActivity.start(EditPersionActivity.this,phone);
                break;

        }
    }

    private void savePersionInfo() {
        if(TextUtils.isEmpty(avater)){
            EasyToast.showToast(getApplicationContext(),"请上传头像");
            return;
        }
        if(TextUtils.isEmpty(nickname)){
            EasyToast.showToast(getApplicationContext(),"请输入昵称");
            return;
        }
        if(TextUtils.isEmpty(phone)){
            EasyToast.showToast(getApplicationContext(),"请绑定手机号码");
            return;
        }
        MyHttpRequest request = new MyHttpRequest(this);
        JSONObject joj = new JSONObject();
        try {
            joj.put("avatar",avater);
            joj.put("nick_name",nickname);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request.put(UrlCenter.USERS_SELF, joj, new DataRequestListener<Object>(Object.class) {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                EventBus.getDefault().post(new MineModifyEntity(avater,nickname));
                EasyToast.showToast(getApplicationContext(),"保存成功");
                finish();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                EasyToast.showToast(getApplicationContext(),strMsg);
            }
        });
    }

    private void showIOSAlertFrag() {
        final IOSAlertListFragment diaFrag = new IOSAlertListFragment();
        String[] strArr = new String[]{"拍照", "从照片库选择"};
        diaFrag.setActionList(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    //拍照
                    case 0:
                        // 3、调用拍照方法
                        PermissionGen.with(EditPersionActivity.this)
                                .addRequestCode(REQ_TAKE_MINE_PHOTO)
                                .permissions(Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                        Manifest.permission.CAMERA
                                ).request();

                        break;
                    //相册
                    case 1:
                        PermissionGen.needPermission(EditPersionActivity.this,
                                REQ_MINE_SELECT_PHOTO,
                                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE}
                        );
                        break;
                }
                diaFrag.dismiss();
            }
        }, strArr).show(getSupportFragmentManager());
    }

    //头像拍照
    @PermissionSuccess(requestCode = REQ_TAKE_MINE_PHOTO)
    private void takePhoto() {
        init(true);
    }
    //选择图库
    @PermissionSuccess(requestCode = REQ_MINE_SELECT_PHOTO)
    private void selectPhoto() {
        init(false);
    }

    private void init(boolean isTake) {
        // 1、创建LQRPhotoSelectUtils（一个Activity对应一个LQRPhotoSelectUtils）
        mLqrPhotoSelectUtils = new LQRPhotoSelectUtils(this, new LQRPhotoSelectUtils.PhotoSelectListener() {
            @Override
            public void onFinish(File outputFile, Uri outputUri, int type) {
                // 4、当拍照或从图库选取图片成功后回调
                sendRequest(type,outputFile.getAbsolutePath());
            }
        }, true);//true裁剪，false不裁剪
        if(isTake==true){
            mLqrPhotoSelectUtils.takePhoto(-1);
        }else{
            mLqrPhotoSelectUtils.selectPhoto(-1);
        }
    }

    private void sendRequest(int type, String absolutePath) {
        //获取队列
        LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(this)
                .setMessage("上传中...")
                .setCancelable(true)
                .setCancelOutside(true);

        upDialog = loadBuilder.create();
        upDialog.show();
        File file = new File(absolutePath);
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        List<Part> partList = new ArrayList<Part>();
        try {
            partList.add(new FilePart("image", file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //生成请求
        MultipartRequest profileUpdateRequest = new MultipartRequest(UrlCenter.IMGAGE, partList.toArray(new Part[partList.size()]), new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                JSONObject jobj = null;
                try {
                    jobj = new JSONObject(s);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                upDialog.cancel();
                avater = jobj.optString("url");
                Glide.with(EditPersionActivity.this).load(avater).into(mCivHead);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                upDialog.cancel();
            }
        });
        //将请求加入队列
        requestQueue.add(profileUpdateRequest);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("requestCode",requestCode+"");
        if (requestCode == NICKNAMECODE && resultCode == BACKNICKNAMECODE) {
            String backnickname = data.getExtras().getString(NICKNAME);
            mTvNickName.setText(backnickname);
            nickname=backnickname;
        } else if (requestCode == REQ_TAKE_MINE_PHOTO || requestCode == REQ_MINE_SELECT_PHOTO||requestCode==REQ_ZOOM_PHOTO) {
            mLqrPhotoSelectUtils.attachToActivityForResult(requestCode, resultCode, data);
        }
    }

}
